package com.zc.redisstream.listener;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.zc.domain.ElectricAlarm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.stream.MapRecord;
import org.springframework.data.redis.connection.stream.ObjectRecord;
import org.springframework.data.redis.connection.stream.RecordId;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.stream.StreamListener;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author zhangcheng
 * @date 2022/9/5 21:54
 * @description
 */
@Component
public class ElectricAlarmStreamListener implements StreamListener<String, ObjectRecord<String,ElectricAlarm>> {
    private final Logger logger = LoggerFactory.getLogger(ElectricAlarmStreamListener.class);

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void onMessage(ObjectRecord<String, ElectricAlarm> message) {
        try {
//            String stream = message.getStream();
//            RecordId messageId = message.getId();
//            Map<String, String> valueMap = message.getValue();
//            logger.info("指标阈值告警消息处理: streamKey: {}, message id: {}, valueMap: {}",stream,messageId,valueMap);
//            // 接收到消息
//            JSONObject jsonObject = new JSONObject();
//            for (String json : valueMap.values()) {
//                jsonObject.putAll(JSON.parseObject(json));
//            }

            String stream = message.getStream();
            RecordId messageId = message.getId();
            ElectricAlarm valueMap = message.getValue();
            logger.info("指标阈值告警消息处理: streamKey: {}, message id: {}, valueMap: {}",stream,messageId,valueMap);
            // 接收到消息

        } catch (Exception e) {
            logger.error("指标阈值告警处理异常", e);
        } finally {
            redisTemplate.opsForStream().delete(message);
        }
    }
}

